/*
# File    :   serial.c
# Author  :   SCHIPS
# Mail    :   schips@dingtalk.com
# Date    :   Mon, Apr 29, 2019  3:48:13 PM
# Platform:   VC
*/


#define _CRT_SECURE_NO_WARNINGS 
#include <iostream>
#include <stdio.h>
#include <windows.h>
#include <string.h>
#include <conio.h>
#include "tchar.h"


void serialUninit(HANDLE hCom)
{
	CloseHandle(hCom);
	return ;
}

HANDLE serialInit(char *ComPath, int BaudRate)
{
    HANDLE hCom;
    hCom = CreateFile(_T(ComPath),		// 设置 COM口
        GENERIC_READ | GENERIC_WRITE,	// 允许读和写
        0,								// 独占方式
        NULL,
        OPEN_EXISTING,					// 打开而不是创建
        0,								// 同步方式
        NULL);
    if(hCom == (HANDLE)-1)
    {
        //printf("[%s] 打开失败!\n", ComPath);
        return FALSE;
    }
    else
    {
        //printf("[%s] 打开成功！\n", ComPath);
    }


    SetupComm(hCom, 20480, 20480);		//输入缓冲区和输出缓冲区的大小都是1024
    
    COMMTIMEOUTS TimeOuts;				//设定读超时    
    TimeOuts.ReadIntervalTimeout = 100;
    TimeOuts.ReadTotalTimeoutMultiplier = 500;
    TimeOuts.ReadTotalTimeoutConstant = 5000;    
    TimeOuts.WriteTotalTimeoutMultiplier = 500;//设定写超时
    TimeOuts.WriteTotalTimeoutConstant = 2000;
    SetCommTimeouts(hCom, &TimeOuts);		//设置超时

    DCB dcb1;
    GetCommState(hCom, &dcb1);
    dcb1.BaudRate = BaudRate;		//波特率  BaudRate

    dcb1.ByteSize = 8;				//每个字节有8位
    dcb1.Parity = NOPARITY;			//无奇偶校验位
    dcb1.StopBits = TWOSTOPBITS;	//两个停止位
    dcb1.fParity = FALSE;
    dcb1.fNull = FALSE;
    SetCommState(hCom, &dcb1);

	return hCom;
}

int ReadFromCOM(HANDLE hCom, unsigned char *str, DWORD wCount)
{
	if(str==NULL)
	{
		return -1;
	}

    DWORD wCount1;
    PurgeComm(hCom, PURGE_TXCLEAR|PURGE_RXCLEAR);//清空缓冲区
	

    if(!ReadFile(hCom, str, wCount, &wCount1, NULL))
    {
        // printf("读串口失败!");
        return FALSE;
    }
	
    if(wCount1 <= 0)
    {
        // printf("读取内容失败!");
    }

	return wCount1;
}

int WriteToCOM(HANDLE hCom, unsigned char *str, DWORD wCount)
{
	ULONG  ulRead;

	if(str==NULL)
	{
		return -1;
	}

    PurgeComm(hCom, PURGE_TXCLEAR|PURGE_RXCLEAR);//清空缓冲区
	

	if (!WriteFile(hCom, str,wCount,&ulRead, NULL))  
    {  
        // printf("读串口失败!");
        return FALSE;
    }  

	return ulRead;
}



#if 1
// for demo
int main()
{
	int i;
	char ComPath[30];
	int BaudRate;
	int ret;
	HANDLE hCom;

	while(1)
	{
		// 使用 std::out 会出现乱码
		printf("请指定 COM口 : ");
		scanf("%s",ComPath);
		printf("请指定波特率 : ");
		scanf("%d",&BaudRate);
		hCom =  serialInit(ComPath, BaudRate);
		if(FALSE != hCom )
		{
			break;
		}
	}

	serialUninit(hCom);

    return 0;
}
#endif


